package com.zengqingfa.sharding.jdbc.demo.sharding.precise;

import com.alibaba.fastjson.JSON;
import com.zengqingfa.sharding.jdbc.demo.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Objects;

/**
 *
 * @fileName: ShardingTablePreciseAlgorithm
 * @author: zengqf3
 * @date: 2021-3-28 21:40
 * @description: 分表算法
 */
@Slf4j
public class ShardingTablePreciseAlgorithm implements PreciseShardingAlgorithm<Timestamp> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Timestamp> shardingValue) {
        log.info("availableTargetNames={}", JSON.toJSONString(availableTargetNames));
        log.info("shardingValue={}", JSON.toJSONString(shardingValue));
        Long timeValue = shardingValue.getValue().getTime();
        if (Objects.isNull(timeValue)) {
            throw new UnsupportedOperationException("preciseShardingValue is null");
        }
        //按月路由
        for (String each : availableTargetNames) {
            String yearAndMonth = DateUtil.getYearAndMonth(timeValue);
            if (each.endsWith(yearAndMonth)) {
                //这里返回回去的就是最终需要查询的表名
                log.info("yearAndMonth={}", yearAndMonth);
                return each;
            }
        }
        return null;
    }
}
